class AccountController < ApplicationController
  require_role "user_admin", :only => [:show, :list, :edit, :update]
  
  layout 'ipm'
  def index
    redirect_to :action => 'list_active'
  end

  def list
    @users = User.find(:all)
    
    
    #page title
    @header_title = 'Accounts'
    #sub menu
    @submenu = 'account'
  end
  
  def list_active
    @users = User.find(:all, :conditions => "active = 1")
    
    
    #page title
    @header_title = 'Accounts'
    #sub menu
    @submenu = 'account'
    render :action => 'list'
  end
  
  def show
    
    @user = User.find(params[:id])
    
    #page title
    @header_title = 'Accounts'
    #sub menu
    @submenu = 'account'
  end
  
  def login
    if logged_in?
      redirect_to :controller => 'project'
      return
    end
    
    return unless request.post?
    self.current_user = User.authenticate(params[:login], params[:password])
    if logged_in?
      if params[:remember_me] == "1"
        self.current_user.remember_me
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      #if not request.env["HTTP_REFERER"] == "http://inno.ath.cx/account/login"
        redirect_back_or_default(:controller => '/project', :action => 'index')
      #else 
       # redirect_to :controller => 'project'
      #end
      flash[:notice] = "Logged in successfully"
    else
      flash[:notice] = "Loging failed."
      end
      
  end

  def signup
    @user = User.new(params[:user])
    return unless request.post?
    @user.save!
    self.current_user = @user
    redirect_back_or_default(:controller => 'project', :action => 'list')
    flash[:notice] = "Thanks for signing up!"
  rescue ActiveRecord::RecordInvalid
    render :action => 'signup'
  end
  
  def logout
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "You have been logged out."
    redirect_back_or_default(:controller => '/account', :action => 'index')
  end
  
  
  def edit
      @user = User.find(params[:id])

      #page title
      @header_title = 'Accounts'
      #sub menu
      @submenu = 'account'
  end

  #
  #update the user table
  def update
      @user = User.find(params[:id])

      #page title
      @header_title = 'Accounts'
      #sub menu
      @submenu = 'account'
      
      params[:roles] = [] if params[:roles].nil?
      roles = params[:roles].collect { |i| Role.find(i) }
      @user.roles = roles
      
      if @user.update_attributes(params[:user])
          flash[:notice] = 'User was successfully updated.'
          redirect_to :action => 'list_active'
      else
          render :action => 'edit'
      end
  end
  
  
  def close
    @user = User.find(params[:id])
    @user.active = false
    @user.save
    
    flash[:notice] = 'User was successfully closed.'
    redirect_to :action => 'list_active'
  end
end
